package auth.controller;

import auth.service.UserService;
import auth.util.RedisUtil;
import com.woniuxy.common.entity.AuthResult;
import com.woniuxy.common.entity.CenterUser;
import com.woniuxy.common.entity.CenterUserExample;
import com.woniuxy.common.entity.User;
import com.woniuxy.common.mapper.CenterUserMapper;
import com.woniuxy.common.utils.JWTUtils;
import com.woniuxy.common.utils.KeyUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

//import com.wnxy.auth.util.RedisUtil;
@RestController
public class UserController {
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private UserService userService;
    //未登录，跳转登录页面，现在使用401提示，不使用这个
    /*@RequestMapping("/skip")
    public Object skip() {
        System.out.println("未登录，跳转登录页面");
        Map<String,Object>result=new HashMap<>();
        result.put("code",302);
        result.put("mes","尚未登录");
        return result;
    }*/
    //登录
    @RequestMapping("/login")
    public AuthResult login(User user) {

        System.out.println("开始验证" + user);
        //获取用户信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken userMes = new UsernamePasswordToken(user.getUname(), user.getPwd());
        try {
            //验证
            subject.login(userMes);
            System.out.println("认证成功");

            //认证成功
            CenterUser centerUser = userService.findUser(user.getUname());
            String token = JWTUtils.createToken(centerUser.getId());
            String refreshToken = KeyUtil.generateKey();
            //保存数据
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("token", token);
            map.put("uname", user.getUname());
            System.out.println(refreshToken);
            System.out.println(map);
            redisUtil.hmset(refreshToken, map);
            redisUtil.expire(refreshToken, 24 * 60 * 60);//单位秒
            return new AuthResult(AuthResult.STATE_SUCCESS, "验证成功", token, refreshToken);
        } catch (UnknownAccountException e) {
            return new AuthResult(AuthResult.STATE_FAIL, "用户名不存在", null, null);
        } catch (IncorrectCredentialsException e) {
            return new AuthResult(AuthResult.STATE_FAIL, "密码错误", null, null);
        } catch (LockedAccountException e) {
            return new AuthResult(AuthResult.STATE_FAIL, "用户审核中", null, null);
        } catch (DisabledAccountException e) {
            return new AuthResult(AuthResult.STATE_FAIL, "账号已被封禁", null, null);
        } catch (AuthenticationException e) {
            return new AuthResult(AuthResult.STATE_FAIL, "认证错误", null, null);
        }
    }

    /*
    注册
     */
    @RequestMapping("/addUser")
    public Object addUser(CenterUser centerUser) {
        Map<String, Object> stringObjectMap = userService.addUser(centerUser);
        return stringObjectMap;
    }
    /*
    密码修改
     */
    @RequestMapping("/alterPass")
    public Object alterPass(HttpServletRequest request, String password, String newpass) {
        String userId;
        try {
            //获取要修改密码的用户id
            userId = JWTUtils.getUserId(request.getHeader("token"));
            if(userId==null||userId.equals("")){
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //修改密码
        Map<String, Object> stringObjectMap = userService.alterPassService(userId, password, newpass);
        return stringObjectMap;
    }
    /*
        退出登录
         */
    @RequestMapping("/lgout")
    public Object lgout(HttpServletRequest request) {
        String refreshtoken;
        try {
            refreshtoken = request.getHeader("refreshtoken");
            if(refreshtoken==null||refreshtoken.equals("")){
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        System.out.println(refreshtoken);
        //退出登录
        Map<String, Object> stringObjectMap = userService.logoutService(refreshtoken);
        return stringObjectMap;
    }

    //角色认证
   /* @RequestMapping("/hasRole/{token}/{role}")
    public boolean hasRole(@PathVariable("token") String token,
                           @PathVariable("role") String role) {
        System.out.println("进行角色认证");
        //查询数据库
		*//*String uname = JWTUtils.getUname(token);
		List<String>roles=new ArrayList<String>();
		roles.add("admin");
		roles.add("student");
		//权限判定
		if(roles.contains(role)) {
			return true;
		}*//*
        return true;
    }*/

    //token刷新
   /* @RequestMapping("/refresh/{refreshToken}/{token}")
    public AuthResult refresh(@PathVariable("refreshToken") String refreshToken,
                              @PathVariable("token") String token) {
        //创建新token
        String newToken = JWTUtils.createToken(JWTUtils.getUserId(token));
        //保存redis
        System.out.println("模拟保存ridis：" + newToken);
        //返回浏览器
        return new AuthResult(AuthResult.STATE_OLD,
                "刷新成功", newToken, refreshToken);
    }*/

}
